package drds.plus.datanode.fetcher;

import drds.plus.datanode.configuration.DataNodeConfigurationManager;
import drds.plus.datanode.configuration.DataSourceWrapper;
import drds.plus.datasource.api.DataSource;

import java.sql.SQLException;

public class DataSourceFetcherImpl implements DataSourceFetcher {
    private DataNodeConfigurationManager dataNodeConfigurationManager;

    public DataSourceFetcherImpl(DataNodeConfigurationManager dataNodeConfigurationManager) {
        this.dataNodeConfigurationManager = dataNodeConfigurationManager;
    }

    public DataSource getDataSource(String dataSourceId) throws SQLException {
        DataSourceWrapper dataSourceWrapper = dataNodeConfigurationManager.dataSourceIdToDataSourceWrapperMap.get(dataSourceId);
        if (dataSourceWrapper != null) {
            return dataSourceWrapper.getDataSource();
        } else {
            DataSource dataSource = dataNodeConfigurationManager.initDataSource(dataNodeConfigurationManager.datasourceManager.getApplicationId(), dataSourceId);
            dataSourceWrapper = new DataSourceWrapper(dataSourceId, null, dataSource);
            dataNodeConfigurationManager.dataSourceIdToDataSourceWrapperMap.put(dataSourceId, dataSourceWrapper);
            return dataSource;
        }
    }

}
